<template>
  <div class="wxTravelEdit">
    <div id="map"></div>
    <div class="my-chang">
      <!-- 左侧天数 -->
      <div class="content-left">
        <div :class="{ action: daySelect == i }" @click="turnFeeConsultation(i)" v-for="i in dayNum" :key="i">
          第{{ i }}天
        </div>
        <!-- <div>
          <i class="el-icon-circle-plus-outline"></i>
        </div> -->
      </div>

      <!-- 右侧详细站数 -->
      <div class="content-right">
        <div class="TargetDay" v-for="i in dayNum" :key="i">
          <span>第{{ i }}天 <i class="el-icon-delete" @click="delDay(i)" v-if="dayNum>1"></i></span>
          <ul>
            <li v-for="(village,j) in cutRoute(i-1)" :key="j">
              <div class="AddTargetUUp" @click="addTarget(i,j)"
                :class="{ ok: villageSelect[0]==i&&(villageSelect[1]==j||villageSelect[1]==j-1)}">
                <img src="@/assets/images/straight-line.png" />
                <i class="el-icon-circle-plus-outline"></i>
                <img src="@/assets/images/straight-line.png" />
              </div>
              <div class="up" @click="villageSelectChg(i,j)" @touchstart.capture="touchStart"
                @touchend.capture="touchMove" data-type="0">
                <img :src="village.image[0]" />
                <div class="flex">
                  <div class="tit">{{ j+1 }}.{{village.villageName}}</div>
                </div>
                <!-- 右移的删除更新 -->
                <div class="SlidingModule">
                  <div class="updata" @click="upDataVigation(i,j)">
                    <i class="el-icon-refresh"></i>
                  </div>
                  <div class="delet" @click="deletVigation(i,j)" v-if="routeline.length>1">
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
              </div>
            </li>
            <div class="AddTargetLow" @click="addTarget(i,j+1)"
              :class="{ ok: villageSelect[0]==i&&villageSelect[1]==cutRoute(i-1).length-1}">
              <img src="@/assets/images/straight-line.png" />
              <i class="el-icon-circle-plus-outline"></i>
              <img src="@/assets/images/straight-line.png" />
            </div>
          </ul>
        </div>
      </div>
      <!-- 下面按钮 -->
      <div class="Navigation">
        <div class="TourismBegins" @click="sureEdit">
          <img src="@/assets/images/edit-icon.png" /><span>修改完成</span>
        </div>
        <!-- <div class="collect">
              <img src="@/assets/images/heart-icon-at.png" alt="">
            </div> -->
      </div>
    </div>


  </div>
</template>

<script>
  window._AMapSecurityConfig = {
    securityJsCode: "1de37d2fc1b761d5ccacf8eee4b0c3b8",
  };
  import AMapLoader from "@amap/amap-jsapi-loader";

  import { getRouteTravelMsg, collectTravel } from "@/api/wechat/navigation";

  export default {
    name: "wxTravelEdit",
    data() {
      return {
        map: null,
        travelId: null,
        userId: null,
        longitude: null,
        latitude: null,
        isFirst: null,
        unUser: 1,
        markerIcon: null,
        routeIndex: -1,
        routeline: [],
        daySelect: 1, //当前天数
        villageSelect: [null, null],
        transparent: 0, // 添加按钮透明度
        startX: 0, //滑动开始
        endX: 0, //滑动结束
      };
    },
    computed: {
      dayNum() {
        return Math.ceil(this.routeline.length / 2)
      }
    },
    created() {
      document.title = "修改行程";
      this.travelId = this.$route.query.travelId;
      this.unUser = this.$route.query.unUser;
      this.userId = this.$route.query.userId;
      this.longitude = this.$route.query.longitude;
      this.latitude = this.$route.query.latitude;
      this.isFirst = this.$route.query.isFirst;

      this.setMap();

      if (this.$store.getters.villagelist && this.$store.getters.villagelist.length > 0) {
        this.routeline = this.$store.getters.villagelist;
        this.setBackChg()
      } else {
        this.getInfo()
      }


    },
    methods: {
      getInfo() {
        getRouteTravelMsg({
          userId: this.userId,
          travelId: this.travelId,
          type: this.unUser,
        }).then(res => {
          this.routeline = res.data
          this.routeline.forEach(village => {
            if (village.villageImage) {
              village.image = village.villageImage.split(',').map(img => {
                return process.env.VUE_APP_BASE_API + img;
              })
            } else {
              village.image = [];
            }
          })
          this.setBackChg()
        })
      },
      setBackChg() {
        let operateInfo = this.$store.getters.operateInfo;
        if (operateInfo.type == 'editAdd') {
          let same = this.routeline.filter(item => {
            return item.villageId == operateInfo.village.villageId
          })
          if (same.length > 0) {
            alert('乡村已存在')
            return false
          }
          this.routeline.splice(operateInfo.index, 0, {
            villageId: operateInfo.village.villageId,
            image: operateInfo.village.villageImage.split(',').map(img => {
              return process.env.VUE_APP_BASE_API + img;
            }),
            villageName: operateInfo.village.villageName,
          })
        } else if (operateInfo.type == 'editReplace') {
          let same = this.routeline.filter(item => {
            return item.villageId == operateInfo.village.villageId
          })
          if (same.length > 0) {
            alert('乡村已存在')
            return false
          }
          this.routeline.splice(operateInfo.index, 1, {
            villageId: operateInfo.village.villageId,
            image: operateInfo.village.villageImage.split(',').map(img => {
              return process.env.VUE_APP_BASE_API + img;
            }),
            villageName: operateInfo.village.villageName,
          })
        }
        this.$store.commit('SET_VIllAGELIST', this.routeline)
        this.$store.commit('SET_OPERATEINFO', {
          village: null,
          type: null,
          index: null
        })
      },
      sureEdit() {
        let villageId = this.routeline.map(item => {
          return item.villageId;
        })
        collectTravel({
          travelId: this.travelId,
          userId: this.userId,
          villageId: villageId.join(','),
          status: true
        }).then(res => {
          alert("修改成功")
          wx.miniProgram.getEnv((envRes) => {
            if (envRes.miniprogram) {
              wx.miniProgram.postMessage({ data: { unUser: 0 } });
            }
          })
          tt.miniProgram.getEnv((envRes) => {
            if (envRes.miniprogram) {
              tt.miniProgram.postMessage({ data: { unUser: 0 } });
            }
          })
          this.$store.commit('SET_ISUNUSER', 0)
          if (this.isFirst) {
            wx.miniProgram.getEnv((envRes) => {
              if (envRes.miniprogram) {
                wx.miniProgram.navigateBack(-1);
              }
            })
            tt.miniProgram.getEnv((envRes) => {
              if (envRes.miniprogram) {
                tt.miniProgram.navigateBack(-1);
              }
            })
          } else {
            this.$router.go(-1)
          }


        })
      },
      cutRoute(i) {
        let routeline = JSON.parse(JSON.stringify(this.routeline));
        return routeline.splice(i * 2, 2)
      },
      villageSelectChg(i, j) {
        this.villageSelect = [i, j];
        this.restSlide();
        let village = this.routeline[(i - 1) * 2 + j]
        this.map.clearMap();
        let villageMarker = new AMap.Marker({
          position: new AMap.LngLat(village.villageLongitude, village.villageLatitude),
          offset: new AMap.Pixel(-10.5, -28),
          icon: this.markerIcon, // 添加 Icon 实例
          title: village.villageName,
        });
        this.map.add(villageMarker)
        this.map.setCenter([village.villageLongitude, village.villageLatitude]);
      },
      setMap() {
        AMapLoader.load({
          key: "c818b1b759eb2cad524fee31e071311c",
          version: "2.0",
          plugins: ["AMap.Geocoder"],
        }).then((AMap) => {
          this.geocoder = new AMap.Geocoder({});
          this.map = new AMap.Map("map", {
            zoom: 11,
            center: [119.65, 29.08],
            mapStyle: "amap://styles/54058aa0a123f042cdab644aaa6e580b",
            showIndoorMap: false,
          });
          this.markerIcon = new AMap.Icon({
            size: new AMap.Size(21, 28), // 图标尺寸
            image: require("../../assets/images/address-zs.png"), // Icon的图像
            imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(21, 28), // 根据所设置的大小拉伸或压缩图片
          });
        }).catch((e) => {
          console.log(e);
        });
      },
      delDay(i) {
        this.routeline.splice((i - 1) * 2, 2)
        this.$store.commit('SET_VIllAGELIST', this.routeline)
      },
      // 点击删除
      deletVigation(i, j) {
        this.restSlide();
        this.villageSelect = [null, null];
        this.routeline.splice((i - 1) * 2 + j, 1)
        this.$store.commit('SET_VIllAGELIST', this.routeline)
      },
      // 点击更新
      upDataVigation(i, j) {
        let village = this.routeline[(i - 1) * 2 + j]
        this.$router.push({
          path: "/wxDest",
          query: {
            longitude: village.villageLongitude,
            latitude: village.villageLatitude,
            enterType: 'editReplace',
            index: (i - 1) * 2 + j
          }
        });
      },
      // 点击添加
      addTarget(i, j) {
        let state1 = this.villageSelect[0] == i && (this.villageSelect[1] == j || this.villageSelect[1] == j - 1)
        let state2 = this.villageSelect[0] == i && this.villageSelect[1] == this.cutRoute(i - 1).length - 1

        if (state1 || state2) {
          this.$router.push({
            path: "/wxDest",
            query: {
              longitude: this.longitude,
              latitude: this.latitude,
              enterType: 'editAdd',
              index: (i - 1) * 2 + j
            }
          });
        }


      },
      // 滚动到对应位置
      turnFeeConsultation(day) {
        // 现实选择了第几天
        this.daySelect = day;
        // 滚动到目标位置
        let TargetDay = document.getElementsByClassName("TargetDay");
        TargetDay[day - 1].scrollIntoView({ behavior: "smooth", block: "start" });
      },

      //滑动开始
      touchStart(e) {
        // 记录初始位置
        this.startX = e.touches[0].clientX;
      },
      //滑动移动
      touchMove(e) {
        // 记录结束位置
        this.endX = e.changedTouches[0].clientX;
        // 左滑大于10距离删除出现
        if (this.startX - this.endX > 10) {
          this.restSlide();
          this.villageSelect = [null, null];
          e.currentTarget.dataset.type = 1;
        } else if (this.startX - this.endX < -10) {
          // 右滑
          e.currentTarget.dataset.type = 0;
        }
      },

      // 滑块复位
      restSlide() {
        let listItems = document.querySelectorAll(
          ".content-right>.TargetDay>ul>li>.up"
        );
        // 复位
        listItems.forEach((i) => {
          i.dataset.type = 0;
        });
      },

    },
  };
</script>
<style>
  .wxTravelEdit .amap-logo,
  .wxTravelEdit .amap-copyright {
    display: none !important;
  }
</style>
<style scoped lang="scss">
  .wxTravelEdit {
    height: 100vh;
    display: flex;
    flex-direction: column;

    #map {
      flex: 1;
    }

    .my-chang {
      background-color: #ffffff;
      padding: 0;
      height: 55%;
      position: relative;

      span {
        font-size: 15px;
      }

      // 整体图标颜色
      i {
        margin-left: 10px;
        color: #a5a6aa;
      }

      .content-left {
        height: calc(100% - 73px);
        background-color: #f0f1f5;
        overflow: scroll;
        display: inline-block;

        &::-webkit-scrollbar {
          width: 0px;
        }

        div {
          padding: 20px;

          i {
            color: #46469e;
            font-size: 16px;
          }
        }

        .action {
          background-color: #ffffff;
        }
      }

      .content-right {
        padding: 20px;
        height: calc(100% - 73px);
        width: calc(100% - 90px);
        text-overflow: ellipsis;
        overflow: scroll;
        display: inline-block;

        &::-webkit-scrollbar {
          width: 0px;
        }

        // 每天模板
        .TargetDay {
          background-color: #ffffff;

          ul {
            padding: 0;
            margin: 20px 0;

            // 每一站模板
            li {
              list-style: none; //去除点
              overflow: hidden;
              position: relative;

              // 上面文字
              .up {
                padding: 7px 8px;
                border-radius: 10px;
                box-shadow: 2px 3px 14px rgba(99, 99, 99, 0.06);
                display: flex;
                justify-content: flex-start;
                /* 全部样式 0.4秒 缓动*/
                transition: 0.4s;

                img {
                  width: 60px;
                  height: 60px;
                  border-radius: 8px;
                }

                // 图片左侧文字
                .flex {
                  margin: 5px 0 0 10px;
                  font-size: 16px;
                  width: calc(100% - 70px);

                  p {
                    // 文本-超出部分: ...
                    text-overflow: ellipsis;
                    // 超出部分: 隐藏
                    overflow: hidden;
                    // 文本不换行
                    white-space: nowrap;

                    margin-top: 6px;
                    color: #8f8f8f;
                    font-size: 12px;
                  }
                }

                // 初始位置
                &[data-type="0"] {
                  transform: translate(0, 0);
                }

                // 移动位置
                &[data-type="1"] {
                  transform: translate(-115px, 0);
                  -webkit-transform: translateX(-115px);
                  // position: relative;
                  // left: -115px;
                }

                .SlidingModule {
                  padding: 20px 15px;
                  display: flex;
                  width: 115px;
                  height: 80px;
                  position: absolute;
                  top: 0;
                  right: -115px;
                  justify-content: space-around;
                  align-content: center;

                  .updata {
                    border-radius: 6px;
                    padding: 11px;
                    background-color: #46469e;

                    i {
                      margin: 0;
                      color: white;
                    }
                  }

                  .delet {
                    border-radius: 6px;
                    padding: 11px;
                    margin-left: 13px;
                    background-color: #e15c5e;

                    i {
                      color: white;
                      margin: 0;
                    }
                  }
                }
              }

              .AddTargetUUp {
                margin: 6px 0;
                height: 10px;
                opacity: 0;
                display: flex;
                align-items: center;

                i {
                  color: #46469e;
                  font-size: 16px;
                  margin: 0;
                }

                img {
                  margin: 0 12px;
                }

                &.ok {
                  opacity: 1;
                }
              }
            }

            .AddTargetLow {
              margin: 6px 0;
              height: 10px;
              opacity: 0;
              display: flex;
              align-items: center;

              i {
                color: #46469e;
                font-size: 16px;
                margin: 0;
              }

              img {
                margin: 0 12px;
              }

              &.ok {
                opacity: 1;
              }
            }
          }
        }
      }

      .Navigation {
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        padding: 15px 17px;
        background-color: #ffffff;
        box-shadow: 0 -3px 4px rgba(70, 70, 159, 0.04);

        .TourismBegins {
          display: flex;
          color: #46469e;
          width: 100%;
          border-radius: 10px;
          background-color: #f5f5f9;
          padding: 10px;
          justify-content: center;
          align-items: center;
          font-size: 16px;

          img {
            height: 14px;
            margin: 0 10px 0 0;
          }
        }

        // .collect {
        //   margin-left: 10px;
        //   text-align: center;
        //   padding: 13px 0;
        //   width: 40px;
        //   display: inline-block;
        //   border-radius: 10px;
        //   background-color: #f5f5f9;
        //   font-size: 0;

        //   img{
        //     height: 16px;
        //   }
        // }
      }
    }


  }
</style>
